package me.zhengjie.modules.fund.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.fund.domain.UserFund;
import me.zhengjie.modules.fund.service.UserFundService;
import me.zhengjie.modules.fund.service.dto.UserFundDto;
import me.zhengjie.modules.fund.service.dto.UserFundQueryCriteria;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Set;

@RestController
@RequestMapping("/api/userfund")
@Api(tags = "工具：我的基金")
public class UserFundController {

    private static final String ENTITY_NAME = "userFund";

    @Resource
    private UserFundService userFundService;

    @ApiOperation("查询我的基金")
    @GetMapping()
    @PreAuthorize("@el.check('userfund:list')")
    public ResponseEntity<Object> query(UserFundQueryCriteria criteria, Pageable pageable) throws Exception {
        criteria.setUserId(SecurityUtils.getCurrentUserId());
        Page<UserFundDto> userFundDtos = userFundService.queryAll(criteria, pageable);
        return new ResponseEntity<>(PageUtil.toPage(userFundDtos), HttpStatus.OK);
    }

    @Log("新增我的基金")
    @ApiOperation("新增我的基金")
    @PostMapping
    @PreAuthorize("@el.check('userfund:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody UserFund resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        resources.setUserId(SecurityUtils.getCurrentUserId());
        userFundService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("更新我的基金")
    @ApiOperation("更新我的基金")
    @PutMapping
    @PreAuthorize("@el.check('userfund:edit')")
    public ResponseEntity<Object> update(@Validated(UserFund.Update.class) @RequestBody UserFund resources) {
        userFundService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除我的基金")
    @ApiOperation("删除我的基金")
    @DeleteMapping
    @PreAuthorize("@el.check('userfund:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> deleteIds) {
        userFundService.delete(deleteIds);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
